<?php

namespace App\Http\Requests\School;

use App\Models\Food;
use App\Models\FoodType;
use Illuminate\Foundation\Http\FormRequest;

/**
 * Class StoreFood
 * @package App\Http\Requests\School
 */
class StoreFood extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => [
                'required',
                'string',
                function ($attribute, $value, $fail) {
                    if (Food::query()->where('status', Food::START_USING)
                        ->where('school_id', \Auth::user()->school_id)
                        ->where('name', $value)->exists()) {
                        return $fail('已存在相同名称的菜品');
                    }
                }
            ],
            'description' => 'string|nullable',
            'supply_type' => [
                'required',
                'array',
                function ($attribute, $value, $fail) {
                    foreach ($value as $item) {
                        if (!in_array($item, Food::SUPPLY_TYPES)) {
                            return $fail('菜品供应类型错误');
                        }
                    }
                }
            ],
            'food_type_id' => [
                'required',
                function ($attribute, $value, $fail) {
                    // 先判断该学校下的菜品种类表中是否存在状态为启用的该菜品种类
                    if (FoodType::where('school_id', \Auth::user()->school_id)
                        ->where('status', 1)->where('id', $value)->doesntExist()) {
                        return $fail('未找到已启用的该菜品种类');
                    }
                }
            ]
        ];
    }

    /**
     * @return array
     */
    public function attributes()
    {
        return [
            'name' => '菜品名称',
            'description' => '菜品描述',
            'supply_type' => '供应类型',
            'food_type_id' => '菜品种类'
        ];
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'name.required' => '请填写:attribute',
            'name.string' => ':attribute数据类型错误',
            'description.string' => ':attribute数据类型错误',
            'supply_type.required' => '请选择:attribute',
            'supply_type.array' => ':attribute参数错误',
            'food_type_id.required' => '请选择:attribute'
        ];
    }
}
